"""
用户交互代理
负责自然语言处理和交互逻辑
"""

from typing import Dict, Any
import re

class UserInteractionAgent:
    """用户交互代理"""
    
    def __init__(self):
        """初始化交互系统"""
        self.context = {}
        self.dialogue_state = "idle"
        self.intent_handlers = {
            'prediction': self._handle_prediction,
            'analysis': self._handle_analysis,
            'optimization': self._handle_optimization
        }
    
    def natural_language_query(self, query: str) -> Dict[str, Any]:
        """
        自然语言查询处理
        参数:
            query: 用户自然语言查询
        返回:
            结构化查询结果
        """
        # 清理输入
        query = query.lower().strip()
        
        # 意图识别
        intent = self._detect_intent(query)
        
        # 参数提取
        params = self._extract_parameters(query, intent)
        
        # 更新对话状态
        self._update_dialogue_state(intent)
        
        # 返回结构化结果
        return {
            'intent': intent,
            'parameters': params,
            'context': self.context,
            'dialogue_state': self.dialogue_state
        }
    
    def _detect_intent(self, query: str) -> str:
        """检测用户意图"""
        patterns = {
            'prediction': r'(预测|forecast|predict)',
            'analysis': r'(分析|analyze|show me)',
            'optimization': r'(优化|optimize|improve)'
        }
        
        for intent, pattern in patterns.items():
            if re.search(pattern, query):
                return intent
        return 'unknown'
    
    def _extract_parameters(self, query: str, intent: str) -> Dict[str, str]:
        """从查询中提取参数"""
        params = {}
        
        # 提取时间相关参数
        time_matches = re.findall(r'(\d+)\s*(天|周|月|年|days?|weeks?|months?|years?)', query)
        if time_matches:
            params['time_period'] = f"{time_matches[0][0]}{time_matches[0][1]}"
        
        # 提取数据相关参数
        data_matches = re.findall(r'(销售|价格|成本|sales|price|cost)', query)
        if data_matches:
            params['data_type'] = data_matches[0]
        
        # 根据意图提取特定参数
        if intent == 'prediction':
            target_match = re.search(r'(预测|predict)\s*(.*?)\s*(的|for)', query)
            if target_match:
                params['target'] = target_match.group(2)
        
        return params
    
    def _update_dialogue_state(self, intent: str) -> None:
        """更新对话状态"""
        if intent != 'unknown':
            self.dialogue_state = intent
    
    def _handle_prediction(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """处理预测意图"""
        # 实现预测逻辑
        return {'action': 'predict', 'params': params}
    
    def _handle_analysis(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """处理分析意图"""
        # 实现分析逻辑
        return {'action': 'analyze', 'params': params}
    
    def _handle_optimization(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """处理优化意图"""
        # 实现优化逻辑
        return {'action': 'optimize', 'params': params}
    
    def get_context(self) -> Dict[str, Any]:
        """获取当前上下文"""
        return self.context
    
    def reset_context(self) -> None:
        """重置上下文"""
        self.context = {}
        self.dialogue_state = "idle"